import React, { useState, useEffect } from 'react'
import './less/ListTable.less'
import { Space, Table, Button,message } from 'antd';
import { ArticleListApi, ArticleDelApi} from '../utils/request/api'
import moment from 'moment';
import { useNavigate } from 'react-router-dom'

// 标题组件
function MyTitle(props) {
  return (
    <>
      <a to='/' target="_blank" href={'http://codesohigh.com:8765/article/' + props.id} className='list_title'>{props.title}</a>
      <p style={{ color: '#999' }}>{props.subTitle}</p>
    </>
  )
}

export default function ListTable() {
  const navigate = useNavigate();
  // 列表数组
  const [arr, setArr] = useState([])
  // 分页函数
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  })
  // 删除文章
  const delFn = (id) => {
    ArticleDelApi({id}).then(res=>{
      if(res.errCode === 0){
        message.success(res.message)
        // 重新刷新页面，要么重新请求这个列表的数据
        getArticleList(pagination.current, pagination.pageSize)
      }
    })
  }
  // 提取请求的代码
  const getArticleList = (current, pageSize) => {
    ArticleListApi({
      num: current,
      count: pageSize
    }).then(res => {
      if (res.errCode === 0) {
        // 更改pagination
        let { num, count, total } = res.data
        setPagination({
          current: num,
          pageSize: count,
          total: total
        })
        // 不对原数据进行操作，因此进行一次深拷贝
        let newArr = JSON.parse(JSON.stringify(res.data.arr))
        let myArr = []
        /* 
        1.要给每个数组项加key,让key=id
        2.需要有一套标签结构，赋予一个属性
         */
        newArr.map((item) => {
          let obj = {
            key: item.id,
            date: moment(item.date).format("YYYY-MM-DD hh:mm:sss"),
            myTitle: <MyTitle title={item.title} subTitle={item.subTitle} id={item.id} />
          }
          myArr.push(obj)
        })
        setArr(myArr)
      }
    })
  }
  // 请求文章数据
  useEffect(() => {
    getArticleList(pagination.current, pagination.pageSize);
  }, [])

  // 分页函数 
  const pageChange = (arg) => {
    getArticleList(arg.current, arg.pageSize);
  }
  const columns = [
    {
      title: '标题',
      dataIndex: 'myTitle',
      key: 'myTitle',
      width: '60%',
      render: (text) => <div>{text}</div>,
    },
    {
      title: '时间',
      dataIndex: 'date',
      key: 'date',
      render: (text) => (
        <>
          <p>{text}</p>
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: text => {
        return (
          <Space size="middle">
            <Button type='primary' onClick={() => navigate('/edit/' + text.key)}>编辑</Button>
            <Button type='danger' onClick={() => delFn(text.key)}>删除</Button>
          </Space>
        )
      },
    },
  ];

  return (
    <div className='list_table'>
      <Table
        columns={columns}
        dataSource={arr}
        onChange={pageChange}
        pagination={pagination}
      />
    </div>
  )
}
